package com.og.vas.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.og.vas.common.annotations.EnableLoginHandle;
import com.og.vas.common.exception.BusinessException;
import com.og.vas.common.result.R;
import com.og.vas.common.result.ResponseEnum;
import com.og.vas.pojo.dto.LoginDTO;
import com.og.vas.pojo.dto.RegisterDTO;

import com.og.vas.pojo.entity.UserInfo;
import com.og.vas.pojo.vo.LoginVO;
import com.og.vas.pojo.vo.UserInfoVO;
import com.og.vas.service.UserInfoService;
import com.og.vas.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xzy
 * @since 2022-01-11
 */
@RestController
@RequestMapping("/admin/userInfo")
@Api(tags = "用户操作相关接口")
public class UserInfoController {

    @Autowired
    UserInfoService service;

    @ApiOperation("测试接口")
    @GetMapping("/test")
    public String test(){
        return "访问成功";
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public R register(@ApiParam(value = "注册对象", required = true)
                      @RequestBody RegisterDTO registerDTO) {
        //重复校验
        service.validityCheck(registerDTO.getIdCardNum(),registerDTO.getPhone());

        //注册
        service.Register(registerDTO);



        return R.ok().message("注册成功");
    }


    @ApiOperation("用户登录")
    @PostMapping("/login")
    public R register(@ApiParam(value = "登录对象", required = true)
                      @RequestBody LoginDTO loginDTO) {

        //校验返回vo
        LoginVO login = service.login(loginDTO);


        //数据返回
        return R.ok().message("登录成功").data("loginVO",login);
    }

    @EnableLoginHandle(identity = 2)
    @ApiOperation(value = "修改权限（超级管理员权限）",
            notes = "op为操作符，1为将普通用户升为管理员，0为将管理员降级为普通用户")
    @PostMapping("/permission")
    public R register(@ApiParam("待修改对象")Integer userId,@ApiParam("op为操作符，1为将普通用户升为管理员，0为将管理员降级为普通用户")Integer op) {

        //操作修改
        service.updatePermission(userId,op);


        return R.ok().message("修改成功");
    }

    @EnableLoginHandle(identity = 1)
    @ApiOperation(value = "用户列表（管理员权限）",notes = "列出所有用户")
    @GetMapping("/list/{page}/{limit}")
    public R register( @ApiParam(value = "当前页码", required = true) @PathVariable Long page,
                       @ApiParam(value = "每页记录数", required = true) @PathVariable Long limit) {

        //操作获取

        Page<UserInfoVO> userInfoVOPage = new Page<>(page, limit);

        IPage<UserInfoVO> list = service.list(userInfoVOPage);

        return R.ok().message("修改成功").data("list",list);
    }
    @EnableLoginHandle(identity = 1)
    @ApiOperation(value = "excle表批量导入新用户（管理员权限）")
    @PostMapping("/impot")
    public R register(@ApiParam(value = "Excel数据字典文件",required = true)
                          @RequestParam("file") MultipartFile file) {

        try {
            InputStream inputStream = file.getInputStream();
            service.imporData(inputStream);

            return R.ok().message("数据导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException((ResponseEnum.UPLOAD_ERROR),e);
        }

    }

    @ApiOperation("校验令牌")
    @GetMapping("/checkToken")
    public R checkToken(HttpServletRequest request) {

        String token = request.getHeader("token");  // 获取令牌(前端将token放入请求头中)


        boolean result = JwtUtils.checkToken(token);

        if (result) {
            return R.ok();
        } else {
            return R.setResult(ResponseEnum.LOGIN_AUTH_ERROR);
        }
    }

    @EnableLoginHandle
    @ApiOperation("修改密码(用户权限)")
    @PostMapping("/UpdatePwd")
    public R updatePwd(HttpServletRequest request,
                       @ApiParam(value = "旧密码", required = true)
                       @RequestParam("oldPwd")
                               String oldpwd,
                       @ApiParam(value = "新密码", required = true)
                       @RequestParam("newPwd")
                               String newpwd
    ){
        //JWT获取id
        Integer userId = JwtUtils.getUserId(request.getHeader("token"));
        //校验修改
        service.updatePwd(userId,oldpwd,newpwd);


        return R.ok().message("修改成功");
    }

}

